<template>
  <view class="container">
    <HeadNav
      back
      title="填写商家信息"
      bg="https://ucp-tcg.com:18001/mc/app/static/shnag_bg2.png"
      bgSize="cover"
    />
    <view class="notice-bar" v-if="rejectReason && isReject">
      审核未通过：{{ rejectReason }}
    </view>
    <view class="form-box">
      <uni-forms
        ref="valiForm"
        :modelValue="valiFormData"
        :border="false"
        labelWidth="110px"
        :rules="rules"
      >
        <view class="content-title">
          <view class="search-icon"></view>
          <text>场地信息</text>
        </view>
        <uni-forms-item label="店铺名称" name="storeName" required>
          <uni-easyinput
            v-model.trim="valiFormData.storeName"
            placeholder="请输入完整店铺名"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="店铺标签" name="storeTags" required>
          <uni-easyinput
            v-model.trim="valiFormData.storeTags"
            placeholder="请输入店铺标签"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="店铺电话" name="phone" required>
          <uni-easyinput
            v-model.trim="valiFormData.phone"
            type="number"
            placeholder="请输入店铺电话"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="所在城市" required name="city">
          <uni-data-picker
            v-model="valiFormData.city"
            :localdata="cityData"
            popup-title="选择城市"
            :map="{ text: 'label', value: 'id' }"
            @change="onPickerchange"
            :readonly="formDisabled"
          >
          </uni-data-picker>
        </uni-forms-item>
        <uni-forms-item label="地址" name="address" required>
          <uni-easyinput
            v-model.trim="valiFormData.address"
            placeholder="请填写地址详情"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <!-- <uni-forms-item label="所属公司" name="company" required>
					<uni-easyinput v-model.trim="valiFormData.company" placeholder="请填写公司名" :inputBorder="false" />
				</uni-forms-item> -->

        <uni-forms-item label="门店描述" name="description" required>
          <uni-easyinput
            type="textarea"
            v-model.trim="valiFormData.description"
            placeholder="最多200个字描述"
            maxlength="200"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <!-- <view class="content-title">
					联系人信息
				</view> -->
        <!-- <uni-forms-item label="联系人姓名" name="contactName" required>
					<uni-easyinput v-model.trim="valiFormData.contactName" placeholder="请填写联系人姓名"
						:inputBorder="false" />
				</uni-forms-item> -->
        <view class="content-title">
          <view class="search-icon"></view>
          <text>照片信息</text>
        </view>
        <uni-forms-item
          label="营业执照照片"
          required
          name="imageValue"
          labelWidth="130px"
          ref="imageValueRef"
        >
          <uni-file-picker
            :title="formDisabled ? '' : '图片大小限制5MB以内'"
            limit="1"
            v-model="valiFormData.imageValue"
            fileMediatype="image"
            @select="e => handleSelect(e, 0)"
            @delete="deleteImg"
            file-extname="png,jpg"
            :del-icon="!formDisabled"
            :disabled="formDisabled"
          >
          </uni-file-picker>
        </uni-forms-item>
        <uni-forms-item
          label="店铺logo图片"
          required
          name="imageValue2"
          labelWidth="130px"
          ref="imageValueRef2"
        >
          <uni-file-picker
            :title="formDisabled ? '' : '图片大小限制5MB以内'"
            limit="1"
            v-model="valiFormData.imageValue2"
            fileMediatype="image"
            @select="e => handleSelect(e, 1)"
            @delete="deleteImg"
            file-extname="png,jpg"
            :del-icon="!formDisabled"
            :disabled="formDisabled"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-forms>
    </view>
    <view class="button-bar">
      <view class="button-bar-btn disabled" v-if="formDisabled"
        >店铺待审核</view
      >
      <view v-else class="button-bar-btn" @tap="formSubmit">
        {{ rejectReason ? '重新申请' : '登记店铺' }}
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { areaListApi, uploadApi } from '@/api/common'
import { applyStoryApi, reApplyStoryApi, storeDetailApi } from '@/api/store'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores'
import HeadNav from '@/components/HeadNav'
const valiForm = ref(null)
const imageValueRef = ref(null)
const imageValueRef2 = ref(null)
const valiFormData = reactive({
  storeName: '',
  address: '',
  description: '',
  storeTags: '',
  phone: '',
  cityCode: '', //市
  provinceCode: '', //省
  // areaCode: '', //区
  imageValue: [],
  imageValue2: [],
  licenseFileId: '',
  storeLogoFileId: '',
  city: ''
})
const cityData = ref([])
const allFilesPath = []
const formDisabled = ref(false)
const isReject = ref(false)
const rejectReason = ref('')
const dataId = ref('')
// 校验规则
const rules = reactive({
  storeName: {
    rules: [
      {
        required: true,
        errorMessage: '店铺名称是必填项'
      }
    ]
  },
  storeTags: {
    rules: [
      {
        required: true,
        errorMessage: '店铺标签是必填项'
      }
    ]
  },
  phone: {
    rules: [
      {
        required: true,
        errorMessage: '店铺电话是必填项'
      },
      {
        format: 'number',
        errorMessage: '店铺电话只能输入数字'
      }
    ]
  },
  city: {
    rules: [
      {
        required: true,
        errorMessage: '所在城市是必填项'
      }
    ]
  },
  address: {
    rules: [
      {
        required: true,
        errorMessage: '地址是必填项'
      }
    ]
  },
  description: {
    rules: [
      {
        required: true,
        errorMessage: '门店描述是必填项'
      }
    ]
  },
  imageValue: {
    rules: [
      {
        validateFunction: (rule, value, data, callback) => {
          const pathArr2 = allFilesPath.filter(
            filterItem => filterItem.index === 0
          )
          if (pathArr2.length === 0) {
            callback('请上传营业执照照片')
          } else {
            return true
          }
        }
      }
    ]
  },
  imageValue2: {
    rules: [
      {
        validateFunction: (rule, value, data, callback) => {
          const pathArr2 = allFilesPath.filter(
            filterItem => filterItem.index === 1
          )
          if (pathArr2.length === 0) {
            callback('请上传店铺logo图片')
          } else {
            return true
          }
        }
      }
    ]
  }
})
const store = useUserStore()

onLoad(options => {
  if (options.auditStatus && options.id) {
    getData(options.id)
    isReject.value = true
  } else if (options.id) {
    formDisabled.value = true
    getData(options.id)
  }
  getCityData()
})
onReady(() => {
  // 需要在onReady中设置规则
  valiForm.value.setRules(rules)
})

const getData = async storyId => {
  try {
    uni.showLoading({
      title: '正在加载...'
    })
    const res = await storeDetailApi(storyId)
    const keys = Object.keys(valiFormData)
    for (const key in res.data) {
      if (keys.includes(key)) {
        valiFormData[key] = res.data[key]
      }
    }
    valiFormData['city'] = res.data.cityCode
    const storeLogoFileUrl = res.data.storeLogoFileUrl
    valiFormData.imageValue2 = []
    if (storeLogoFileUrl) {
      valiFormData.imageValue2.push({
        name: 'storeLogoFileUrl',
        extname: storeLogoFileUrl
          .substring(storeLogoFileUrl.lastIndexOf('.') + 1)
          .toLowerCase(),
        url: storeLogoFileUrl
      })
    }

    const licenseFileUrl = res.data.licenseFileUrl
    valiFormData.imageValue = []
    if (licenseFileUrl) {
      valiFormData.imageValue.push({
        name: 'licenseFileUrl',
        extname: licenseFileUrl
          .substring(licenseFileUrl.lastIndexOf('.') + 1)
          .toLowerCase(),
        url: licenseFileUrl
      })
    }
    rejectReason.value = res.data.reject
    dataId.value = res.data.id
    uni.hideLoading()
  } catch (error) {
    console.log(error)
    uni.hideLoading()
  }
}

const getCityData = async () => {
  const res = await areaListApi()
  const result = []
  for (const province of res.data) {
    const provinceNode = {
      ...province,
      children: []
    }
    result.push(provinceNode)
    // 处理市级数据
    if (province.children && Array.isArray(province.children)) {
      for (const city of province.children) {
        const cityNode = {
          id: city.id,
          label: city.label,
          value: city.value
        }
        provinceNode.children.push(cityNode)
      }
    }
  }

  cityData.value = result
}

const formSubmit = () => {
  // console.log('valiFormData', valiFormData)
  imageValueRef.value.onFieldChange()
  imageValueRef2.value.onFieldChange()
  valiForm.value
    .validate()
    .then(async res => {
      uni.showLoading({
        title: '正在提交...',
        mask: true
      })

      for (const obj of allFilesPath) {
        try {
          const uploadRes = await uploadFileApi(obj.path)
          if (obj.index === 0) {
            valiFormData.licenseFileId = uploadRes.id
          }
          if (obj.index === 1) {
            valiFormData.storeLogoFileId = uploadRes.id
          }
        } catch (e) {
          console.log(e)
          uni.hideLoading()
          return uni.showToast({
            icon: 'none',
            title: '上传文件失败,服务器错误'
          })
        }
      }
      if (rejectReason.value) {
        valiFormData.id = dataId.value
        await reApplyStoryApi(valiFormData)
      } else {
        await applyStoryApi(valiFormData)
      }
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        showCancel: false,
        content: '提交成功，请等待后台审核通过',
        success: function (res) {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    })
    .catch(err => {
      console.log('err', err)
      uni.showToast({
        icon: 'none',
        title: err.length > 1 ? '表单填写有误，请检查' : err.message
      })
    })
}

const onPickerchange = e => {
  valiFormData.provinceCode = e.detail.value[0].value
  valiFormData.cityCode = e.detail.value[1].value
  // valiFormData.areaCode = e.detail.value[2].value
}

const uploadFileApi = path => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: uploadApi(),
      filePath: path,
      name: 'file',
      header: {
        Authorization: store.token
      },
      formData: {
        type: 'stories'
      },
      success: uploadFileRes => {
        const { data, code } = JSON.parse(uploadFileRes.data)
        if (code === 200) {
          resolve(data)
        } else {
          reject(code)
        }
      },
      fail: error => {
        reject(error)
      }
    })
  })
}

const handleSelect = (e, index) => {
  // console.log('e', e)
  allFilesPath.push({
    path: e.tempFilePaths[0],
    index
  })
  if (index === 0) {
    imageValueRef.value.onFieldChange()
  }
  if (index === 1) {
    imageValueRef2.value.onFieldChange()
  }
}

const deleteImg = e => {
  const index = allFilesPath.findIndex(item => item.path === e.tempFilePath)
  if (index > -1) {
    allFilesPath.splice(index, 1)
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #eeeeee;
  font-family: PingFangSC-Regular, sans-serif;
}
.notice-bar {
  display: flex;
  width: 100%;
  box-sizing: border-box;
  flex-direction: row;
  align-items: center;
  padding: 20rpx 24rpx;
  margin-bottom: 20rpx;
  color: #a94442;
  background-color: #f2dede;
  border-color: #ebccd1;
  font-size: 28rpx;
}

.form-box {
  padding: 32rpx;
  padding-bottom: 80rpx;
  box-sizing: border-box;

  .content-title {
    padding-left: 0;
    padding-bottom: 24rpx;
    margin-bottom: 24rpx;
    font-size: 32rpx;
    border-bottom: 2rpx solid #d5d5d4;
    display: flex;
    gap: 24rpx;
    align-items: center;
    .search-icon {
      width: 16rpx;
      height: 32rpx;
      background-image: url('https://ucp-tcg.com:18001/mc/app/static/icon_zs.png');
      background-repeat: no-repeat;
      background-size: cover;
    }
  }

  .time-box {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .time-item {
      background-color: #fff;
      border-radius: 20rpx;
      border: 2rpx solid #b0b0b0;
      padding: 0 32rpx;
    }
  }

  .readonly-text {
    font-size: 28rpx;
    box-sizing: border-box;
    padding: 0 10rpx;
    min-height: 70rpx;
    line-height: 70rpx;
    position: relative;
  }
}

.button-bar {
  width: 100%;
  display: flex;
  justify-content: center;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;

  .button-bar-btn {
    font-family: PingFangSC-Regular, sans-serif;
    background-color: #bb9f5e;
    color: #fff;
    font-size: 28rpx;
    padding: 16rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50%;
    border-radius: 12rpx;
    letter-spacing: 2rpx;
    background-image: url('https://ucp-tcg.com:18001/mc/app/static/tabbg-l.png');
    background-repeat: no-repeat;
    background-size: contain;

    &.disabled {
      opacity: 0.6;
    }
  }
}

::v-deep .uni-data-tree-input .input-value {
  background-color: #e3e3e3;
  border: 0 none;
}

::v-deep .uni-forms-item__content .uni-easyinput__content {
  background-color: #e3e3e3 !important;
}

::v-deep .uni-forms-item__content .uni-easyinput__content.is-disabled {
  color: #3a3a3a !important;
}

::v-deep .uni-easyinput__content-textarea {
  padding-left: 20rpx;
}
::v-deep .uni-easyinput__content .content-clear-icon .uniui-clear {
  color: #3a3a3a !important;
}

::v-deep .uni-file-picker .file-picker__box .file-picker__box-content {
  background-color: #fff;
}

::v-deep .uni-file-picker .uni-file-picker__header {
  padding-top: 8px;
}

::v-deep .uni-file-picker .uni-file-picker__container {
  background-color: #e8e8e8;
  margin: 0;
  .file-picker__box-content {
    border-color: #707070 !important;
  }
}

::v-deep .uni-date-x.uni-date-single {
  background-color: #e3e3e3;
}

::v-deep .uni-date-editor--x__disabled {
  opacity: 1;
}

::v-deep .uni-date-editor--x__disabled .uni-date-x.uni-date-single {
  color: #3a3a3a;
}
</style>
